﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;

namespace LyricsFinder
{
    public class LyricsFinder
    {
        public string GetLyrics(string songName, string album, string genre)
        {
            string lyrics = string.Empty;

            try
            {
                if (!string.IsNullOrEmpty(genre) && genre.ToUpper().Contains("KANNADA"))
                {
                    string url = "http://www.google.com/search?hl=kn&lr=&as_qdr=all&q=site%3Akannadalyrics.com+" + HttpUtility.UrlEncode(album + " - " + songName) + "&aq=f&aqi=&aql=&oq=";
                    string response = GetContent(url);

                    HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
                    htmlDoc.LoadHtml(response);

                    HtmlAgilityPack.HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes("//div[@id='ires']//a");
                    if (null != nodes)
                    {
                        string kannadLyricsURL = nodes[0].Attributes["href"].Value;

                        lyrics = ExtractLyrics(GetContent(kannadLyricsURL), songName);

                    }
                }
            }
            catch (Exception ex)
            {
                lyrics = "An exception occured while processing the request. " + "\n" + ex.ToString();
            }

            return lyrics;
        }

        private string ExtractLyrics(string response, string songName)
        {
            string lyrics = string.Empty;

            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(response);

            HtmlAgilityPack.HtmlNode mainNode = htmlDoc.DocumentNode.SelectSingleNode("//div[@id='main']");

            if (null != mainNode)
            {
                HtmlAgilityPack.HtmlNodeCollection titles = mainNode.SelectNodes("./div/h2");
                if (null != titles)
                {
                    foreach (HtmlAgilityPack.HtmlNode node in titles)
                    {
                        string title = node.InnerText;
                        if (title.Contains(songName))
                        {
                            HtmlAgilityPack.HtmlNodeCollection links = node.SelectNodes("./a");
                            if (null != links && links.Count > 0)
                            {
                                lyrics = ExtractLyrics(GetContent("http://www.kannadalyrics.com/" + links[0].Attributes["href"].Value), songName);
                            }
                        }
                    }
                }
            }


            if (lyrics == string.Empty)
            {
                lyrics = mainNode.InnerHtml;
            }



            return lyrics;
        }

        private string GetContent(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Proxy = WebRequest.DefaultWebProxy;
            request.Proxy.Credentials = CredentialCache.DefaultCredentials;

            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = new CookieContainer(); // enable cookies

            HttpWebResponse res = (HttpWebResponse)request.GetResponse();

            Stream resst = res.GetResponseStream();
            StreamReader sr = new StreamReader(resst);
            string content = sr.ReadToEnd();

            return content;
        }
    }
}
